package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.Budget;
import com.gxuwz.zhangjiahui.entity.Funds;
import com.gxuwz.zhangjiahui.entity.Project;
import com.gxuwz.zhangjiahui.entity.Team;
import com.gxuwz.zhangjiahui.service.IBudgetService;
import com.gxuwz.zhangjiahui.service.IFundsService;
import com.gxuwz.zhangjiahui.service.IProjectService;
import com.gxuwz.zhangjiahui.service.ITeamService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
@RequestMapping("/funds")
public class FundsController {

    @Autowired
    private IFundsService iFundsService;
    @Autowired
    private IBudgetService iBudgetService;
    @Autowired
    private ITeamService iTeamService;
    @Autowired
    private IProjectService iProjectService;


    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @ResponseBody
    @RequestMapping(value = "/findFunds")
    public ModelAndView findFunds(ModelAndView modelAndView, Page page, Integer pageNumber, Funds funds,
                                    @Param("fundsId") String fundsId,
                                    @Param("key") Integer key,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Funds> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("funds_id");
        // 进行模糊查询!!!
        if(fundsId != null && fundsId != ""){
            wrapper.like("funds_id", fundsId);
            request.getSession().setAttribute("fundsId", fundsId);
        }else {
            request.getSession().setAttribute("fundsId", "");
        }
        // 判断是否是学是，如果是只能看到自己带领的项目
        if(key != null && key == 1){
            // 获取学生学号
            String stuNo = (String) request.getSession().getAttribute("studentNo");
            Team team = new Team();
            team.setStuNo(stuNo);
            // 查找对应学号的团队
            team = iTeamService.findTeamByStuNo(team);
            // 根据学号和团队号，查找项目ID
            Project project = new Project();
            project.setStuNo(stuNo);
            project.setTeamId(team.getTeamId());
            List<Project> projectList = iProjectService.findProjectByStuNoOrTeamId(project);
            for(Project project1: projectList){
                wrapper.eq("project_id", project1.getProjectId()).or();
            }
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Funds> fundsIPage = iFundsService.selectFundsPage(page, wrapper);
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+fundsIPage.getTotal());
        System.out.println("总页数"+fundsIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)fundsIPage.getPages());
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)fundsIPage.getPages()];
        for(int i=0; i< (int)fundsIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", fundsIPage.getTotal());
        List<Funds> fundsList = fundsIPage.getRecords();
        modelAndView.addObject("fundsList", fundsList);
        System.out.println("fundsList = "+fundsList);

        // 根据年度查询预算方案
        Budget budget = new Budget();
        // 存放当前年份
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        budget.setBudgetYear(formatter.format(new Date()));
        List<Budget> budgetList = iBudgetService.findBudgetByYear(budget);
        modelAndView.addObject("budgetList", budgetList);

        modelAndView.setViewName("funds/funds_list");
        return modelAndView;
    }



    /**
     * 添加/修改 信息
     * @param funds
     * @return
     */
    @PostMapping(value = "/addEditFunds")
    public ModelAndView addEditFunds(Funds funds, HttpServletRequest request, ModelAndView modelAndView) {
        Funds funds1 = iFundsService.findFundsById(funds);
        System.out.println("funds = " + funds);
        System.out.println("funds1 = " + funds1);
        // 新增信息
        if(funds1 == null){
            System.out.println("进入新增");
            try {
                iFundsService.addFunds(funds);
                request.getSession().setAttribute("result", "addTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "addFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        // 修改用户信息
        if(funds1 != null){
            System.out.println("进入修改");
            try {
                if(funds1.getFundsNowMoney() != 0){
                    // 进行经费累积
                    funds.setFundsNowMoney(funds1.getFundsNowMoney() + funds.getFundsNowMoney());
                }
                iFundsService.updateFundsById(funds);
                request.getSession().setAttribute("result", "editTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "editFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        modelAndView.setViewName("redirect:/funds/findFunds");
        return modelAndView;
    }



    /**
     * 删除信息
     * @param fundsId
     * @return
     */
    @GetMapping(value = "/deleteFunds")
    public ModelAndView deleteFunds(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("fundsId") String fundsId) {
        Funds funds = new Funds();
        funds.setFundsId(fundsId);
        try {
            iFundsService.deleteFundsById(funds);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/funds/findFunds");
        return modelAndView;
    }

}
